package com.example.config;

import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 请求头配置类
 * 职责：管理HTTP请求头，提供反爬虫支持
 * 功能：
 * - 提供随机User-Agent
 * - 管理完整的请求头信息
 * - 支持动态生成请求头
 */
@Component
public class HeaderConfig {
    
    private final String[] userAgents = {
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0"
    };

    private final Random random = new Random();

    /**
     * 获取随机的请求头
     * @param referer 来源URL
     * @return 请求头Map
     */
    public Map<String, String> getHeaders(String referer) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        headers.put("Cache-Control", "max-age=0");
        headers.put("Connection", "keep-alive");
        headers.put("Sec-Fetch-Dest", "document");
        headers.put("Sec-Fetch-Mode", "navigate");
        headers.put("Sec-Fetch-Site", "none");
        headers.put("Sec-Fetch-User", "?1");
        headers.put("Upgrade-Insecure-Requests", "1");
        headers.put("Referer", referer);
        headers.put("User-Agent", getRandomUserAgent());
        return headers;
    }

    /**
     * 获取随机User-Agent
     * @return 随机的User-Agent字符串
     */
    private String getRandomUserAgent() {
        return userAgents[random.nextInt(userAgents.length)];
    }
} 